<template>
  <div class="route-navigation">
    <div class="route-header">
      <h3>行程导航</h3>
      <el-button v-if="!isNavigating" type="primary" @click="startNavigation" :disabled="!routeData">
        开始导航
      </el-button>
      <el-button v-else type="danger" @click="stopNavigation">
        结束导航
      </el-button>
    </div>
    
    <div class="route-info" v-if="routeData">
      <div class="info-item">
        <span class="label">总距离：</span>
        <span class="value">{{ routeData.distance_text }}</span>
      </div>
      <div class="info-item">
        <span class="label">预计时间：</span>
        <span class="value">{{ routeData.estimated_time }}</span>
      </div>
      <div class="info-item">
        <span class="label">剩余距离：</span>
        <span class="value">{{ remainingDistance }}</span>
      </div>
      <div class="info-item">
        <span class="label">剩余时间：</span>
        <span class="value">{{ remainingTime }}</span>
      </div>
    </div>
    
    <div class="navigation-steps" v-if="isNavigating && navigationSteps.length">
      <div class="current-step">
        <div class="step-icon">
          <i :class="getCurrentStepIcon()"></i>
        </div>
        <div class="step-content">
          <div class="step-distance">{{ currentStep.distance }}米后</div>
          <div class="step-instruction">{{ currentStep.instruction }}</div>
        </div>
      </div>
      
      <div class="next-steps">
        <div v-for="(step, index) in getNextSteps()" :key="index" class="next-step">
          <i :class="getStepIcon(step.action)"></i>
          <span>{{ step.instruction }}</span>
        </div>
      </div>
    </div>
    
    <div class="map-container">
      <div id="navigation-map" style="width: 100%; height: 300px;"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  routeData: {
    type: Object,
    default: () => ({})
  },
  startPoint: {
    type: Object,
    required: true
  },
  endPoint: {
    type: Object,
    required: true
  }
})

const isNavigating = ref(false)
const map = ref(null)
const navigationSteps = ref([])
const currentStepIndex = ref(0)
const currentStep = ref({})
const remainingDistance = ref('--')
const remainingTime = ref('--')
const userLocation = ref(null)
const watchId = ref(null)

onMounted(() => {
  initMap()
})

onUnmounted(() => {
  if (watchId.value) {
    navigator.geolocation.clearWatch(watchId.value)
  }
})

function initMap() {
  if (window.AMap) {
    map.value = new window.AMap.Map('navigation-map', {
      zoom: 15,
      center: [props.startPoint.lng, props.startPoint.lat]
    })
    
    // 添加起点和终点标记
    new window.AMap.Marker({
      position: [props.startPoint.lng, props.startPoint.lat],
      map: map.value,
      icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png'
    })
    
    new window.AMap.Marker({
      position: [props.endPoint.lng, props.endPoint.lat],
      map: map.value,
      icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png'
    })
  }
}

function startNavigation() {
  if (!navigator.geolocation) {
    ElMessage.error('您的浏览器不支持地理定位')
    return
  }
  
  isNavigating.value = true
  ElMessage.success('导航已开始')
  
  // 开始监听用户位置
  watchId.value = navigator.geolocation.watchPosition(
    updateUserLocation,
    handleLocationError,
    {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 1000
    }
  )
  
  // 模拟导航步骤（实际应用中应该从路线规划API获取）
  navigationSteps.value = [
    { distance: 200, instruction: '直行200米', action: 'straight' },
    { distance: 150, instruction: '右转进入XX路', action: 'turn-right' },
    { distance: 500, instruction: '直行500米', action: 'straight' },
    { distance: 100, instruction: '左转到达目的地', action: 'turn-left' }
  ]
  
  currentStepIndex.value = 0
  currentStep.value = navigationSteps.value[0]
}

function stopNavigation() {
  isNavigating.value = false
  if (watchId.value) {
    navigator.geolocation.clearWatch(watchId.value)
    watchId.value = null
  }
  ElMessage.info('导航已结束')
}

function updateUserLocation(position) {
  const { latitude, longitude } = position.coords
  userLocation.value = { lat: latitude, lng: longitude }
  
  // 更新地图中心点
  if (map.value) {
    map.value.setCenter([longitude, latitude])
    
    // 添加或更新用户位置标记
    if (!window.userMarker) {
      window.userMarker = new window.AMap.Marker({
        position: [longitude, latitude],
        map: map.value,
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/loc.png'
      })
    } else {
      window.userMarker.setPosition([longitude, latitude])
    }
  }
  
  // 计算剩余距离和时间（简化计算）
  updateRemainingInfo()
}

function handleLocationError(error) {
  console.error('定位失败:', error)
  ElMessage.error('定位失败，请检查定位权限')
}

function updateRemainingInfo() {
  // 这里应该根据实际位置计算剩余距离和时间
  // 简化处理，使用模拟数据
  remainingDistance.value = '1.2公里'
  remainingTime.value = '5分钟'
}

function getCurrentStepIcon() {
  if (!currentStep.value.action) return 'el-icon-location'
  
  const iconMap = {
    'straight': 'el-icon-top',
    'turn-left': 'el-icon-back',
    'turn-right': 'el-icon-right'
  }
  
  return iconMap[currentStep.value.action] || 'el-icon-location'
}

function getStepIcon(action) {
  const iconMap = {
    'straight': 'el-icon-top',
    'turn-left': 'el-icon-back',
    'turn-right': 'el-icon-right'
  }
  
  return iconMap[action] || 'el-icon-location'
}

function getNextSteps() {
  return navigationSteps.value.slice(currentStepIndex.value + 1, currentStepIndex.value + 3)
}
</script>

<style scoped>
.route-navigation {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.route-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.route-header h3 {
  margin: 0;
  color: #333;
}

.route-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.info-item {
  display: flex;
  justify-content: space-between;
}

.label {
  color: #666;
  font-size: 14px;
}

.value {
  font-weight: bold;
  color: #333;
}

.navigation-steps {
  margin-bottom: 20px;
}

.current-step {
  display: flex;
  align-items: center;
  padding: 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 10px;
  margin-bottom: 10px;
}

.step-icon {
  font-size: 24px;
  margin-right: 15px;
}

.step-content {
  flex: 1;
}

.step-distance {
  font-size: 14px;
  opacity: 0.9;
}

.step-instruction {
  font-size: 18px;
  font-weight: bold;
}

.next-steps {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 10px;
}

.next-step {
  display: flex;
  align-items: center;
  padding: 8px 0;
  color: #666;
  font-size: 14px;
}

.next-step i {
  margin-right: 10px;
  width: 20px;
}

.map-container {
  border-radius: 8px;
  overflow: hidden;
}
</style>
